<template>
  <div>
    <tablePaging :tableItem="tableItem" :operationItem="operationItem">
      <template v-slot:contentHeaderCustom="scope">
        <div style="padding:20px 20px 0 20px">
          <div class="flex-jc-s-b">
            <div class="flex" style="align-items: center;">
              <span>批次号:{{ route.query.batchNum || 0 }}</span>
              <span class="labelIcon-primary margin-l-r-10px">学员数量:{{ route.query.studentNum || 0 }}</span>
              <span :class="route.query.payFlag == 1 ? 'labelIcon-primary' : 'labelIcon-danger'">
                {{ route.query.payFlag == 1 ? '已缴费' : '未缴费' }}
              </span>
              <span class="labelIcon-primary margin-l-r-10px">缴费金额：{{ examineObj.payPrice || 0 }}</span>
              <el-tooltip class="box-item" effect="dark" placement="top"
                :visible="examineObj.payPrice != examineObj.studentTotalPrice">
                <template #content>
                  <span>请注意当前学员总价不等于批次缴费金额</span>
                </template>
                <span
                  :class="examineObj.payPrice == examineObj.studentTotalPrice ? 'labelIcon-primary' : 'labelIcon-danger'">
                  学员总价：{{ examineObj.studentTotalPrice || 0 }}
                </span>
              </el-tooltip>

              <span class="edit-payPrice" style="cursor: pointer;" @click="editPayPrice"
                v-show="route.query.type != 'look'"><svg-icon icon-class="edit"
                  style="margin-right: 2px;"></svg-icon>修改</span>

            </div>
            <!--            <el-button type="primary" @click="router.go(-1)" text>返回</el-button>-->
          </div>
          <div style="margin-top: 10px">
            <el-button v-hasPermi="[$button.batchbatchcheckStudent || '']" type="primary" @click="checkStudent"
              :disabled="checkStudentkDisable || route.query.type == 'look'">{{ approved ? '审核通过' : '取消通过' }}</el-button>
            <el-button v-hasPermi="[$button.batchbatchlinedate || '']" type="primary" @click="setExpireDate"
              :disabled="approved || route.query.type == 'look'">设置账号期限</el-button>
            <el-button v-hasPermi="[$button.batchbatchbankType || '']" type="primary" @click="setBankType"
              :disabled="approved || route.query.type == 'look'">设置题库类型</el-button>
            <el-button v-hasPermi="[$button.batchbatchunitprice || '']" type="primary" @click="setStudentPrice()"
              :disabled="approved || route.query.type == 'look'">设置学员单价</el-button>
            <el-button v-hasPermi="[$button.batchbatchbankType || '']" type="danger" @click="deleteBatch()"
              :disabled="deleteBatchFlag || route.query.type == 'look'">批量删除</el-button>
          </div>
          <div class="left-title" style="margin-top: 30px">学员列表</div>
        </div>
      </template>
      <template v-slot:actionCustom="scope">
        <el-button v-if="scope.scope.scope.row.openId && route.query.type !== 'look' " v-hasPermi="[$button.batchbatchbind || '']" style="padding: 2px" :size="'small'" type="primary"
                   @click="cancelBindHandle(scope)" text>解绑</el-button>
        <el-button v-if=" route.query.type !== 'look'" style="padding: 2px" :size="'small'" type="primary"
                   @click="editCourseHandle(scope)" text>修改科目</el-button>
        <el-button v-if="scope.scope.scope.row.status === '4' && route.query.type !== 'look'" style="padding: 2px" :size="'small'" type="primary"
                   @click="disableHandle(scope)" text>启用</el-button>
        <el-button v-if="scope.scope.scope.row.status === '2' && route.query.type !== 'look'" style="padding: 2px" :size="'small'" type="danger"
                   @click="disableHandle(scope)" text>禁用</el-button>
        <el-button v-if="scope.scope.scope.row.status !== '2' && route.query.type !== 'look'" v-hasPermi="[$button.batchbatchremove || '']" style="padding: 2px" :size="'small'" type="danger"
                   @click="delHandle(scope)" text>删除</el-button>
      </template>
      <template v-slot:footerCustom>
        <div class="text-center" style="padding-top:15px">
          <el-button @click="router.go(-1)">返回</el-button>
        </div>
      </template>

    </tablePaging>
  </div>

  <!-- 设置过期时间 -->
  <el-dialog v-model="setExpireDialog.dialogVisible" title="设置账号期限" @close="setExpireDialog.close">
    <el-form ref="expireForm" label-width="100px" :model="setExpireDialog.request" :rules="setExpireDialog.rules">
      <el-form-item label="账号期限" prop="date">
        <div class="block">
          <el-date-picker v-model="setExpireDialog.request.date" placeholder="请选择账号期限" type="daterange"
            value-format="YYYY-MM-DD" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期"/>
        </div>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="setExpireDialog.close">取 消</el-button>
        <el-button type="primary" @click="setExpireDialog.confirm">
          确 定
        </el-button>
      </span>
    </template>
  </el-dialog>

  <!-- 设置题库类型 -->
  <el-dialog v-model="bankTypeDialog.dialogVisible" title="设置题库类型" @close="bankTypeDialog.close">
    <el-form ref="bankTypeForm" label-width="100px" :model="bankTypeDialog.request" :rules="bankTypeDialog.rules">
      <el-form-item label="题库类型" prop="courseBankTypeId">
        <el-select v-model="bankTypeRequest.courseBankTypeId" placeholder="请选择题库类型">
          <el-option v-for="item, index in courseBankOption" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="bankTypeDialog.close">取 消</el-button>
        <el-button type="primary" @click="bankTypeDialog.confirm">
          确 定
        </el-button>
      </span>
    </template>
  </el-dialog>

  <!-- 设置学员单价 -->
  <el-dialog v-model="studentPriceDialog.dialogVisible" title="设置学员单价" @close="studentPriceDialog.close">
    <el-form ref="studentPrice" label-width="100px" :model="studentPriceDialog.request" :rules="studentPriceDialog.rules">
      <el-form-item label="学员单价" prop="unitPayPrice">
        <el-input v-model="studentPriceDialog.request.unitPayPrice" placeholder="请输入学员单价">
        </el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="studentPriceDialog.close">取 消</el-button>
        <el-button type="primary" @click="studentPriceDialog.confirm">
          确 定
        </el-button>
      </span>
    </template>
  </el-dialog>

  <!-- 缴费 -->
  <el-dialog v-model="paymentDialog.dialogVisible" title="缴费" @close="paymentDialog.close(), payInfo.payProofUrl = ''">
    <!-- 缴费表单 -->
    <el-form ref="paymentForm" :label-position="labelPosition" label-width="100px" :model="payInfo" :rules="paymentRules">
      <el-form-item label="缴费金额" prop="payPrice">
        <el-input @input="payInfo.payPrice = keepTwoPoint(payInfo.payPrice, 30)" maxlength="30" v-model="payInfo.payPrice"
          placeholder="请输入缴费金额" />
      </el-form-item>

      <el-form-item label="缴费日期" prop="payDate">
        <div class="block">
          <el-date-picker v-model="payInfo.payDate" type="date" placeholder="请选择缴费日期" format="YYYY/MM/DD"
            value-format="YYYY-MM-DD" />
        </div>
      </el-form-item>

      <el-form-item label="缴费凭据">
        <el-upload class="avatar-uploader" :action="uploadFileUrl" :headers="headers" :show-file-list="false"
          :on-success="handleUploadSuccess" :on-error="handleUploadError" accept=".jpeg,.png,.jpg,.bmp">
          <img style="width: 150px; height: 150px; object-fit: scale-down;" v-if="payInfo.payProofUrl"
            :src="payInfo.payProofUrl" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon">
            <Plus />
          </el-icon>
        </el-upload>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="paymentDialog.close">取 消</el-button>
        <el-button type="primary" @click="paymentDialog.confirm">
          确 定
        </el-button>
      </span>
    </template>
  </el-dialog>
  <!--  修改科目-->
  <el-dialog v-model="studentCourseDialog.dialogVisible" title="修改科目" :before-close="studentCourseDialog.close">
    <div>
      <el-form ref="studentCourseForm" label-width="100px" :model="studentCourseRequest" :rules="studentCourseRules">
        <el-form-item label="考试科目" prop="courseName">
          <el-select v-model="studentCourseRequest.courseName" value-key="id" placeholder="请选择科目" clearable filterable
                     @change="setCourseBankOption">
            <el-option v-for="item in courseListOptions" :key="item.id" :label="item.name" :value="item">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="题库类型" prop="courseBankTypeId">
          <el-select v-model="studentCourseRequest.courseBankTypeId" placeholder="请选择题库类型" clearable filterable>
            <el-option v-for="item in courseBankOption" :key="item.id" :label="item.name" :value="item.id"/>
          </el-select>
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="studentCourseDialog.close">取 消</el-button>
        <el-button type="primary" @click="studentCourseDialog.confirm"> 确 定</el-button>
      </span>
    </template>
  </el-dialog>
</template>
<script setup>
import tablePaging from '@/views/common/component/table-paging'
import { onMounted, reactive, ref, provide, nextTick, computed } from 'vue'
import {
  tableItem,
  examineObj,
  operationItem,
  getPayAndTotalPrice,
  checkStudentApi,
  bankSetApi,
  setExpireDateApi,
  verifyCourseIdApi,
  batchDelApi,
  setUnitPayPrice,
  paymentApi,
  studentCourseEditApi,
  studentStatusChangeApi, batchCancelBindApi
} from './const.js'
import { Plus, Search } from "@element-plus/icons-vue";
import { ElMessage, ElMessageBox } from 'element-plus'
import newDialog from "@/hooks/useDialog";
import { configBankApi } from "../../../question/rule/const.js";
import { useRouter, useRoute } from 'vue-router'
import $button from '@/button'
import { getToken } from "@/utils/auth";
import { keepTwoPoint } from "../../../../../utils/checkInput.js";
import {courseListApi} from '../../student/const'
const headers = ref({ Authorization: "Bearer " + getToken() });
const uploadFileUrl = ref(import.meta.env.VITE_APP_BASE_API + "/common/upload"); // 上传文件服务器地址
const route = useRoute()
const router = useRouter()
const { proxy } = getCurrentInstance();
// 搜索
operationItem.menuArray[0].handle = () => {
  tableItem.pageInfo.paging()
}
onMounted(() => {
  tableItem.pageInfo.request.id = route.query.id || ''
  tableItem.pageInfo.paging()
})

// 禁用今天之前的时间
const pickerOptions = (time) => {
  const today = new Date();
  return time.getTime() < today.getTime() - 8.64e7;

};
const selectList = ref([])
const courseBankOption = ref([])
let idList = [];
let courseIdList = [];
const rows = ref([])

provide("rows", rows)
//========校验选择学员是否合理,并将选择的学员数据保存=========
//#region
let checkStudentkDisable = ref(true)
let approved = ref(true)
let deleteBatchFlag = ref(true)
let statusSum = 0;
const courseListOptions = ref([])

tableItem.selectChange = (row) => {
  selectList.value = row
  statusSum = 0;
  idList.length = 0;
  courseIdList.length = 0;
  selectList.value.forEach(function (item) {
    idList.push(item.conCourseId)
    courseIdList.push(item.courseId)
    statusSum += parseInt(item.status)
  })

  //没选择任何学员，或者选择的学员的审核状态不统一时，该按钮不可点击
  if (idList.length != 0 && (statusSum == idList.length || statusSum == idList.length * 2 || statusSum == idList.length * 3)) {
    approved = statusSum == idList.length; //只有审核通过的学员可以选择到期日期和题库类型
    deleteBatchFlag = !approved
    checkStudentkDisable.value = false
    if (statusSum == idList.length * 3) {
      checkStudentkDisable.value = true
      deleteBatchFlag = false
    }
  } else {
    checkStudentkDisable.value = true
    approved = true
  }
}
//#endregion

//========处理审核通过功能=========
//#region
function checkStudent() {
  const requestData = {
    batchId: selectList.value[0].batchId + "",
    status: 3 - selectList.value[0].status + "",
    idList,
  }
  checkStudentApi(requestData).then((result) => {
    ElMessage.success("操作成功")
    rows.value = selectList.value;//将选中的行传送给table，让他保持选中
    tableItem.pageInfo.paging()
  });
}
//#endregion

//========处理设置到期时间=========
//#region
//表单校验规则
const expireRules = reactive({
  date: [
    { required: true, message: '请选择到期时间', trigger: 'blur' },
  ],
})
const expireRequest = reactive({
  date: '',
  "startDate": computed(() => {
    if (setExpireDialog.request.date[0])
      return setExpireDialog.request.date[0] + " 00:00:00"
  }),
  "lineDate": computed(() => {
    if (setExpireDialog.request.date[1])
      return setExpireDialog.request.date[1] + " 23:59:59"
  }),
  idList
})
const expireForm = ref('')
const setExpireDialog = newDialog(expireForm, expireRequest, expireRules)
//点击按钮事件处理函数
function setExpireDate() {
  setExpireDialog.request.date = ''
  setExpireDialog.show();
}
//API请求处理函数
setExpireDialog.doConfirm = (request) => {
  setExpireDateApi(request).then((result) => {
    ElMessage({ message: result.msg, type: "success" })
    setExpireDialog.close()
    rows.value = selectList.value;//将选中的行传送给table，让他保持选中
    tableItem.pageInfo.paging()
  })
}
//#endregion

//========处理设置题库类型=========
//#region
// 题库类型参数
const bankTypeRequest = reactive({
  courseBankTypeId: "",
  idList,
})
const bankTypeForm = ref('')
const bankRules = {
  courseBankTypeId: [
    { required: true, message: '请选择题库类型', trigger: 'change' },
  ],
}
const bankTypeDialog = newDialog(bankTypeForm, bankTypeRequest, bankRules)
bankTypeDialog.doConfirm = (request) => {
  bankSetApi(request).then((res) => {
    ElMessage.success(res.msg || '操作成功')
    rows.value = selectList.value; //将选中的行传送给table，让他保持选中
    tableItem.pageInfo.paging()
    bankTypeDialog.close()
  })
}
// 校验课程类型
function showCourseBankOption() {
  configBankApi({ courseId: selectList.value[0].courseParentId || '' }).then((result) => {
    courseBankOption.value = result.rows || []
    bankTypeDialog.show()
  })
}

//点击设置题库类型选项的处理函数
function setBankType() {
  verifyCourseIdApi({ idList: courseIdList }).then((result) => {
    showCourseBankOption()
  })

}

//#endregion

//========处理设置学员单价=========
//#region
//表单校验规则
const studentPriceRules = reactive({
  unitPayPrice: [
    { required: true, message: '请设置学员单价', trigger: 'blur' },
  ],
})

//请求数据包
const studentPriceRequest = reactive({
  unitPayPrice: "",
  idList
})
const studentPrice = ref('')
const studentPriceDialog = newDialog(studentPrice, studentPriceRequest, studentPriceRules)

//点击按钮事件处理函数
function setStudentPrice() {
  studentPriceDialog.show()

}

//点击确定，发送axios请求
studentPriceDialog.doConfirm = (request) => {
  setUnitPayPrice(request).then((result) => {
    ElMessage.success('操作成功');
    tableItem.pageInfo.paging()
    studentPriceDialog.close()
  })
}
//#endregion

//更改缴费金额
//#region

//表单校验规则

function editPayPrice() {
  paymentDialog.show()
  console.log("=============object", tableItem.tableData.data);
  payInfo.id = route.query.id;
}

const paymentRules = reactive({
  payPrice: [
    { required: true, message: '请输入缴费金额', trigger: 'blur' },
  ],
  payDate: [
    { required: true, message: '请先择日期', trigger: 'blur' },
  ],
})

//payment 的 http数据包
const payInfo = reactive({
  id: "",
  payPrice: "",
  payDate: "",
  payProofUrl: ""
})

const paymentForm = ref('')
const paymentDialog = newDialog(paymentForm, payInfo, paymentRules);

//缴费凭证上传成功的回调函数
function handleUploadSuccess(response) {
  payInfo.payProofUrl = response.url
  ElMessage({ message: "上传成功", type: 'success' })
}

//缴费凭证上传失败的回调函数
function handleUploadError(Error) {
  ElMessage.error("上传失败")
}

//表单确认提交
paymentDialog.doConfirm = (request) => {
  paymentApi(request).then((result) => {
    let response = result
    paymentDialog.close()
    ElMessage({ message: response.msg, type: "success" })
    tableItem.pageInfo.paging()
  });
}

// 修改科目
const studentCourseRequest = reactive({
  id: '',
  courseId: '',
  courseName: '',
  courseBankTypeId: '',
  courseParentId: ''
})
const studentCourseForm = ref('')
const studentCourseRules = {
  courseName: [
    { required: true, message: '请选择科目', trigger: 'change' },
  ],
  courseBankTypeId: [
    { required: true, message: '请选择题库类型', trigger: 'change' },
  ],
}
const studentCourseDialog = newDialog(studentCourseForm, studentCourseRequest, studentCourseRules)
studentCourseDialog.doConfirm = (request) => {
  studentCourseEditApi(request).then((res) => {
    ElMessage.success(res.msg || '操作成功')
    tableItem.pageInfo.paging()
    studentCourseDialog.close()
  })
}

function setCourseListOptions() {
  let dataRequest = {
    levelNum: 3,
    parentId: '',
    disableFlag: 0
  }
  courseListApi(dataRequest).then(res => {
    courseListOptions.value = res.rows
  })
  configBankApi({ courseId: studentCourseRequest.courseParentId }).then((result) => {
    courseBankOption.value = result.rows
  })
}

function setCourseBankOption(item) {
  if(item) {
    studentCourseRequest.courseParentId !== item.parentId? studentCourseRequest.courseBankTypeId = '' : ''
    studentCourseDialog.request.courseId = item.id
    studentCourseDialog.request.courseName = item.name
    studentCourseRequest.courseParentId = item.parentId
    configBankApi({ courseId: studentCourseRequest.courseParentId }).then((result) => {
      courseBankOption.value = result.rows
    })
  } else {
    studentCourseRequest.courseParentId = ''
    studentCourseRequest.courseBankTypeId = ''
    courseBankOption.value = []
  }
}

//批量删除
function deleteBatch() {
  proxy.$modal.confirm("确定批量删除?").then(() => {
    batchDelApi({ idList }).then(res => {
      ElMessage.success('操作成功');
      tableItem.pageInfo.paging()
    })
  })
}

//禁用/启用
const disableHandle = (scope) => {
  let row = scope.scope.scope.row
  let text = row.status === "2" ? "禁用" : "启用";
  proxy.$modal.confirm('确认要' + text + '【' + row.name + '】吗?').then(function () {
    let dataRequest = {
      id: row.conCourseId,
      status: row.status === '2' ? '4' : '2'
    }
    return studentStatusChangeApi(dataRequest);
  }).then(() => {
    proxy.$modal.msgSuccess(text + "成功");
    tableItem.pageInfo.paging()
  }).catch(() => { });
}

//单个删除
const delHandle = (scope) => {
  let row = scope.scope.scope.row
  proxy.$modal.confirm('确定删除【' + row.name + '】？').then(() => {
    batchDelApi({ idList: [row.conCourseId] }).then(res => {
      ElMessage.success('操作成功');
      tableItem.pageInfo.paging()
    })
  })
}

//微信解绑
const cancelBindHandle = (scope) => {
  let row = scope.scope.scope.row
  proxy.$modal.confirm('确定微信解绑【' + row.name + '】？').then(() => {
    batchCancelBindApi({ idList: [row.conCourseId] }).then(res => {
      ElMessage.success('操作成功');
      tableItem.pageInfo.paging()
    })
  })
}

//修改科目
const editCourseHandle = (scope) => {
  let row = scope.scope.scope.row
  studentCourseRequest.id = row.conCourseId
  studentCourseRequest.courseId = row.courseId
  studentCourseRequest.courseName = row.courseName
  studentCourseRequest.courseBankTypeId = row.courseBankTypeId
  studentCourseRequest.courseParentId = row.courseParentId
  studentCourseDialog.show()
  setCourseListOptions()
}

//日期限制
function disabledDate(time) {
  if (time.getTime() < new Date().getTime()) {
    return time.getTime() <= new Date().getTime() - 1 * 8.64e7;
  }
}
</script>

<style>
.edit-payPrice {
  padding: 0px 8px;
  border-radius: 2px;
  text-align: center;
  color: #409eff;
  height: 18px;
  line-height: 15px;
  font-size: 14px;
  background-color: #f9fcff;
  font-family: PingFang SC;
  text-decoration: underline;
}

.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 150px;
  height: 150px;
  text-align: center;
}
</style>
